<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { searchBooks } from '@/api/user'
import { ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

interface Book {
  bookId: number
  title: string
  author: string
  description: string
  categoryName: string
  wordCount: number
  publishDate: number
  coverImage: string
}

const searchResults = ref<Book[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = 20  // 固定每页20条
const searchQuery = ref('')

// 添加 props 定义
const props = defineProps<{
  keyword?: string
}>()

// 获取搜索结果
const fetchSearchResults = async () => {
  loading.value = true
  try {
    searchQuery.value = props.keyword || route.query.keyword as string || ''
    if (!searchQuery.value) {
      ElMessage.warning('搜索关键词不能为空')
      router.push('/')
      return
    }

    const res = await searchBooks({
      keyword: searchQuery.value,
      pageNumber: currentPage.value,
      pageSize: pageSize
    })

    if (res.data) {
      searchResults.value = res.data.results
      total.value = res.data.total
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('获取搜索结果失败')
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.query.keyword,
  (newKeyword) => {
    if (newKeyword !== searchQuery.value) {
      fetchSearchResults()
    }
  }
)

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchSearchResults()
}

// 处理图书点击
const handleBookClick = (bookId: number) => {
  router.push({
    path: '/user/book-detail',
    query: { id: bookId }
  })
}

// 修改作者点击处理函数
const handleAuthorClick = (event: Event, author: string) => {
  event.stopPropagation() // 阻止事件冒泡
  router.push({
    path: '/user/author-books',
    query: { author }
  })
}

// 添加日期格式化函数
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 添加返回函数
const handleBack = () => {
  router.back()
}

onMounted(() => {
  fetchSearchResults()
})
</script>

<template>
  <div class="search-results-container">
    <!-- 搜索结果头部 -->
    <div class="search-header">
      <h2>为您找到 {{ total }} 个"{{ searchQuery }}"相关结果</h2>
      <el-button class="back-button" text @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        返回上一页
      </el-button>
    </div>

    <!-- 搜索结果列表 -->
    <div class="result-list" v-loading="loading">
      <template v-if="searchResults.length">
        <div
          v-for="book in searchResults"
          :key="book.bookId"
          class="book-item"
        >
          <div class="book-cover" @click="handleBookClick(book.bookId)">
            <img :src="book.coverImage" :alt="book.title">
          </div>
          <div class="book-info">
            <div class="book-header">
              <h3 class="book-title" @click="handleBookClick(book.bookId)">{{ book.title }}</h3>
              <span class="category-tag">{{ book.categoryName }}</span>
            </div>
            <div class="book-meta">
              <span class="word-count">{{ book.wordCount }}万字</span>
              <span class="separator">|</span>
              <span class="author" @click="handleAuthorClick($event, book.author)">{{ book.author }}</span>
              <span class="separator">|</span>
              <span class="status">已完结</span>
              <span class="separator">|</span>
              <span class="completion-date">{{ formatDate(book.publishDate) }} 完结</span>
            </div>
            <p class="book-description">{{ book.description }}</p>
          </div>
        </div>
      </template>
      <el-empty v-else description="暂无搜索结果" />

      <!-- 分页器 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :pager-count="7"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-results-container {
  width: 100%;
  padding: 0;
  min-height: calc(100vh - 70px);
  background-color: #fff;
}

.search-header {
  padding: 12px 0;
  margin-bottom: 0;
  background-color: #fff;
  position: relative;
}

.search-header h2 {
  width: 60%;
  margin: 0 25% 0 auto;
  font-size: 13px;
  color: #999;
  font-weight: normal;
}

.result-list {
  background: #fff;
  width: 60%;
  margin: 0 25% 0 auto;
  padding: 0;
}

.book-item {
  display: flex;
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
}

.book-cover {
  width: 120px;
  height: 160px;
  margin-right: 20px;
  flex-shrink: 0;
  cursor: pointer;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 2px;
  transition: transform 0.3s ease;
}

.book-cover:hover img {
  transform: scale(1.05);
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.book-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.book-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  font-weight: bold;
  cursor: pointer;
}

.book-title:hover {
  color: #409EFF;
}

.category-tag {
  padding: 2px 8px;
  background-color: #fff;
  color: #409EFF;
  border: 1px solid #409EFF;
  border-radius: 4px;
  font-size: 12px;
}

.book-meta {
  color: #999;
  font-size: 14px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.separator {
  margin: 0 8px;
  color: #ddd;
}

.book-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0 0 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.pagination {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-pagination) {
  font-weight: normal;
  font-size: 14px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ffd04b;
  color: #333;
  font-weight: bold;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #ffd04b;
}

:deep(.el-pagination.is-background .el-pager li) {
  margin: 0 4px;
  min-width: 32px;
  border-radius: 4px;
  font-weight: normal;
  background-color: #fff;
}

.author {
  cursor: pointer;
  transition: color 0.3s;
}

.author:hover {
  color: #409EFF;
}

.completion-date {
  color: #999;
}

.back-button {
  position: absolute;
  right: 20%;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.back-button:hover {
  color: #409EFF;
}
</style> 